<?php
declare(strict_types=1);

namespace Core\HyperfUnit;


use Zms\Unit\Arr;
use Hyperf\HttpServer\Contract\RequestInterface;
use function Hyperf\Config\config;

/**
 * Url处理工具
 * Class Arr
 * @package Core\Method
 */
class Url
{
    /**
     * 创建一个URL
     * @param string $path
     * @param array $param
     * @return string
     */
    public static function create(string $path, array $param = []): string
    {
        if (empty($param)) {
            return $path;
        }
        return $path . '?' . http_build_query($param);
    }


    /**
     * 记住当前参数
     * @param string $path
     * @param array $param
     * @return string
     */
    public static function current(string $path, array $param = []): string
    {
        $query = container(RequestInterface::class)->query();
        $newsParam = Arr::merge($query, $param);
        foreach ($newsParam as $key => $val) {
            if ($val === '' || is_null($val)) {
                unset($newsParam[$key]);
            }
        }
        return empty($newsParam) ? $path : $path . '?' . http_build_query($newsParam);
    }


    /**
     * 获取当前url
     * @return string
     */
    public static function currentUri(): string
    {
        /**
         * @var RequestInterface $query
         */
        $query = container(RequestInterface::class);
        $path = $query->getUri()->getPath();
        $query = $query->getUri()->getQuery();
        return $query ? ($path . '?' . $query) : $path;
    }


    /**
     * 本地文件转URL
     * @param string $file
     * @return string|null
     */
    public static function LocalFileToUrl(string $file): ?string
    {
        $document_root = config('server.settings.document_root');//获取根目录
        if (str_ends_with($document_root, "/")) {
            $document_root = mb_substr($document_root, 0, -1);
        }
        if (str_starts_with($file, $document_root)) {
            return configure('system.host') . mb_substr($file, mb_strlen($document_root));
        } else {
            return null;
        }
    }
}

